#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QThread>
#include <Qmessagebox>
#include <qfiledialog>
#include "sendfile.h"
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //初始化
    ui->ip->setText("127.0.0.1");
    ui->port->setText("8989");
    ui->progressBar->setRange(0,100);
    ui->progressBar->setValue(0);
    setWindowTitle("客户端");
    //创建线程对象
    QThread* t = new QThread;
    //创建任务对象
    sendfile* worker = new sendfile;

    worker->moveToThread(t);

    connect(this , &MainWindow::SendFile , worker,&sendfile::SendFile);

    connect(this , &MainWindow::StartConnect , worker , &sendfile::connectServer);
    //处理子线程发出的信号
    connect(worker , &sendfile::connectOK , this ,[=](){
        QMessageBox::information(this , "连接服务器", "已成功连接服务器");
    });
    connect(worker , &sendfile::gameover , this, [=](){
        t->quit();
        t->wait();
        worker->deleteLater();
        t->deleteLater();
    });
    connect(worker , &sendfile::current_percent , ui->progressBar , &QProgressBar::setValue);

    t->start();
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_connect_clicked()
{
    QString ip = ui->ip->text();
    unsigned short port = ui->port->text().toUShort();
    emit StartConnect(port , ip);
}


void MainWindow::on_select_file_clicked()
{
    QString path = QFileDialog::getOpenFileName();
    if (path.isEmpty())
    {
        QMessageBox::warning(this , "打开文件","选择的文件路径不能为空");
        return;
    }

    ui->file_pass->setText(path);
}


void MainWindow::on_send_file_clicked()
{
    emit SendFile(ui->file_pass->text());
}

